﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using System.Drawing;
using Silvermoon.Shapes;
using Silvermoon.UI;

namespace Silvermoon.Windows.Styles
{
    /// <summary>
    /// Style for all kinds of controls derived from Control or ChromeControl.
    /// </summary>
    public class Style : StyleBase, IDisposable
    {
        public Color? Color { get; set; }
        public Color? TextColor { get; set; }
        public Shape Background { get; set; }
        public Shape Chrome { get; set; }
        public int? Opacity { get; set; }
        public bool? Enabled { get; set; }
        public bool? Visible { get; set; }
        public VisualStateManager StateManager { get; set; }
        public Margin Margin { get; set; }
        public Rectangle? Bounds { get; set; }

        /// <summary>
        /// Set to true to always force to set to the given text color, even if the control has a text color other than Color.Empty.
        /// </summary>
        public bool ForceTextColor;

        /// <summary>
        /// Set to true to always force to set to the given  color, even if the control has a color other than Color.Empty.
        /// </summary>
        public bool ForceColor;


        public virtual void Dispose()
        {
            DisposeObject(Chrome);
            DisposeObject(Background);
            Chrome = null;
            Background = null;
            GC.SuppressFinalize(this);

        }

        protected void DisposeObject(IDisposable obj)
        {
            if (obj != null) obj.Dispose();
        }

        ~Style()
        {
            Dispose();
        }


        public override void Apply(Control c)
        {
            if (StateManager != null && !c.HasStateManager) c.StateManager = StateManager;
            if (Enabled.HasValue) c.Enabled = Enabled.Value;
            if (Visible.HasValue) c.Visible = Visible.Value;
            if (Opacity.HasValue) c.Opacity = Opacity.Value;
            if (Margin != null && !c.HasMargin) c.Margin = Margin;
            if (Bounds.HasValue) c.Bounds = Bounds.Value;

            ChromeControl cc = c as ChromeControl;
            if (cc != null)
            {
                if (Background != null) cc.Background = Background.Clone();
                if (Chrome != null) cc.Chrome = Chrome.Clone();
            }
            if (Color.HasValue && (ForceColor || c.Color.IsEmpty)) c.Color = Color.Value;
            if (TextColor.HasValue &&  (ForceTextColor|| c.TextColor.IsEmpty)) c.TextColor = TextColor.Value;
        }
    }
}
